package com.icinfo.cloud.provider.punish.config.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.icinfo.cloud.common.core.page.PageResponse;
import com.icinfo.cloud.provider.common.config.OrgConfig;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.punish.common.client.IUserCenterClient;
import com.icinfo.cloud.provider.punish.common.client.dto.PunishListPageDto;
import com.icinfo.cloud.provider.punish.common.client.vo.PunishListPageVo;
import com.icinfo.cloud.provider.punish.config.dto.*;
import com.icinfo.cloud.provider.punish.config.enums.DiscretionApplyCaseTypeEnum;
import com.icinfo.cloud.provider.punish.config.enums.DiscretionRuleApplyTypeEnum;
import com.icinfo.cloud.provider.punish.config.enums.DiscretionRuleConfigTypeEnum;
import com.icinfo.cloud.provider.punish.config.enums.DiscretionTypeEnum;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigOrgRegulatoryDiscretionMapper;
import com.icinfo.cloud.provider.punish.config.model.ConfigOrgRegulatoryDiscretion;
import com.icinfo.cloud.provider.punish.config.model.ConfigOrgRegulatoryDiscretionRule;
import com.icinfo.cloud.provider.punish.config.service.IConfigOrgRegulatoryDiscretionRuleService;
import com.icinfo.cloud.provider.punish.config.service.IConfigOrgRegulatoryDiscretionService;
import com.icinfo.cloud.provider.punish.config.vo.ConfigOrgRegulatoryDiscretionDetailVo;
import com.icinfo.cloud.provider.punish.config.vo.ConfigOrgRegulatoryDiscretionPageVo;
import com.icinfo.cloud.provider.punish.config.vo.ConfigOrgRegulatoryDiscretionRuleCountVo;
import com.icinfo.cloud.provider.punish.config.vo.ConfigOrgRegulatoryDiscretionRuleVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseReasonMainRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CasePartiesRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseReasonMainRecordVo;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author HKxxx
 * @date 2024/1/31 15:18
 */
@Slf4j
@Service
public class ConfigOrgRegulatoryDiscretionServiceImpl extends MyBatisServiceSupport implements IConfigOrgRegulatoryDiscretionService {
    @Resource
    private ConfigOrgRegulatoryDiscretionMapper configOrgRegulatoryDiscretionMapper;
    @Resource
    private IConfigOrgRegulatoryDiscretionRuleService configOrgRegulatoryDiscretionRuleService;

    @Resource
    private ICasePartiesRecordService casePartiesRecordService;

    @Resource
    private ICaseReasonMainRecordService caseReasonMainRecordService;

    @Resource
    private IUserCenterClient userCenterClient;

    @Resource
    private OrgConfig orgConfig;


    @Override
    public PageResponse<ConfigOrgRegulatoryDiscretionPageVo> regulatoryDiscretionPage(ConfigOrgRegulatoryDiscretionPageDto dto) {
        //初始化筛选catalogIds容器，用于后续事项筛选
        Set<String> includesCatalogIds = new HashSet<>();
        Set<String> excludesCatalogIds = new HashSet<>();
        //处理需要筛选的catalogIds集合
        dealCurrentOrgPunishListFilterCatalogIds(dto, includesCatalogIds, excludesCatalogIds);

        //查询检查事项列表
        PageResponse<PunishListPageVo> punishPageList = getCurrentOrgPunishPageList(dto, includesCatalogIds, excludesCatalogIds);
        List<String> catalogIds = punishPageList.getData().stream()
                .map(PunishListPageVo::getCatalogId).collect(Collectors.toList());

        if (CollUtil.isEmpty(catalogIds)) {
            return PageResponse.empty();
        }
        //构建 自由裁量配置map key-> catalogId value->配置对象
        Map<String, ConfigOrgRegulatoryDiscretion> discretionMap = getCurrentOrgDiscretionByCatalogIds(catalogIds)
                .stream()
                .collect(Collectors.toMap(ConfigOrgRegulatoryDiscretion::getRegulatoryCatalogId, Function.identity()));
        //构建ruleMap key->catalogId value->该部门事项对市级裁量的数量对象
        Map<String, ConfigOrgRegulatoryDiscretionRuleCountVo> ruleMap = configOrgRegulatoryDiscretionRuleService.getCurrentOrgRuleCountByCatalogIds(catalogIds)
                .stream()
                .collect(Collectors.toMap(ConfigOrgRegulatoryDiscretionRuleCountVo::getRegulatoryCatalogId, Function.identity()));
        //转换对象响应数据
        return punishPageList.convert(t -> new ConfigOrgRegulatoryDiscretionPageVo(t, discretionMap, ruleMap));
    }

    /**
     * 根据catalogIds查询当前部门的自由裁量配置数据
     *
     * @param catalogIds 事项catalogId
     * @return 自由裁量配置数据
     */
    private List<ConfigOrgRegulatoryDiscretion> getCurrentOrgDiscretionByCatalogIds(List<String> catalogIds) {
        if (CollUtil.isEmpty(catalogIds)) {
            return Collections.emptyList();
        }
        Example example = new Example(ConfigOrgRegulatoryDiscretion.class);
        example.createCriteria()
                .andEqualTo("orgCode", orgConfig.getSsfj())
                .andIn("regulatoryCatalogId", catalogIds);
        return configOrgRegulatoryDiscretionMapper.selectByExample(example);
    }

    /**
     * 查询检查事项列表
     *
     * @param dto                分页参数
     * @param catalogIds         包含的catalogIds容器
     * @param excludesCatalogIds 排除的catalogIds容器
     * @return
     */
    private PageResponse<PunishListPageVo> getCurrentOrgPunishPageList(ConfigOrgRegulatoryDiscretionPageDto dto,
                                                                       Set<String> catalogIds, Set<String> excludesCatalogIds) {
        PunishListPageDto punishListPageDto = new PunishListPageDto();
        punishListPageDto.setPageNum(dto.getPageNum());
        punishListPageDto.setLength(dto.getLength());
        punishListPageDto.setOrgCode(orgConfig.getSsfj())
                .setListName(dto.getRegulatoryName())
                .setCatalogIds(catalogIds)
                .setExcludesCatalogIds(excludesCatalogIds)
                .setTerritoryCode(dto.getTerritoryCode())
                .setListCode(dto.getRegulatoryCode())
                .setMainSonType(dto.getMainSonType());
        return userCenterClient.getPunishListInfo(punishListPageDto);
    }

    /**
     * 处理事项列表筛选catalogIds
     *
     * @param catalogIds         包含的catalogIds容器
     * @param excludesCatalogIds 排除catalogIds容器
     */
    private void dealCurrentOrgPunishListFilterCatalogIds(ConfigOrgRegulatoryDiscretionPageDto dto, Set<String> catalogIds, Set<String> excludesCatalogIds) {
        if (Objects.isNull(dto.getDiscretionType()) && StrUtil.isBlank(dto.getAlreadyCityConfig())) {
            return;
        }
        // 初始化筛选范围集合
        List<DiscretionScreenRangeDto> screenRangeList = new LinkedList<>();
        // 是否启用
        DiscretionScreenRangeDto discretionTypeScreenRange = screenDiscretionType(dto.getDiscretionType());
        if (!discretionTypeScreenRange.isNull()) {
            screenRangeList.add(discretionTypeScreenRange);
        }
        // 是否配置
        DiscretionScreenRangeDto alreadyCityConfigScreenRange = screenAlreadyCityConfig(dto.getAlreadyCityConfig());
        if (!alreadyCityConfigScreenRange.isNull()) {
            screenRangeList.add(alreadyCityConfigScreenRange);
        }
        // 将排除的catalogId取并集  指定的catalogId取交集
        handleOperationCatalogIds(catalogIds, excludesCatalogIds, screenRangeList);


    }

    /**
     * 将排除的catalogId取并集  指定的catalogId取交集
     *
     * @param catalogIds         指定的catalogId容器
     * @param excludesCatalogIds 排除catalogIds容器
     * @param screenRangeList    经过筛选的catalogId集合
     */
    private static void handleOperationCatalogIds(Set<String> catalogIds, Set<String> excludesCatalogIds, List<DiscretionScreenRangeDto> screenRangeList) {
        Set<String> includeCatalogIds = new HashSet<>();
        Set<String> excludeCatalogIds = new HashSet<>();
        for (DiscretionScreenRangeDto scope : screenRangeList) {
            // 第一次循环赋值
            if (CollUtil.isEmpty(includeCatalogIds)) {
                includeCatalogIds = scope.getCatalogIds();
            } else if (!scope.getCatalogIds().isEmpty()) {
                // 取交集
                includeCatalogIds = new HashSet<>(CollUtil.intersection(includeCatalogIds, scope.getCatalogIds()));
            }
            // 取并集
            excludeCatalogIds.addAll(scope.getExcludesCatalogIds());
        }
        //赋值筛选条件
        catalogIds.addAll(includeCatalogIds);
        excludesCatalogIds.addAll(excludeCatalogIds);
    }

    /**
     * 筛选是否配置规则
     */
    private DiscretionScreenRangeDto screenAlreadyCityConfig(String alreadyCityConfig) {
        DiscretionScreenRangeDto scopeDto = new DiscretionScreenRangeDto();
        if (StrUtil.isBlank(alreadyCityConfig)) {
            return scopeDto;
        }
        // 找到已经配置规则的catalogIds
        List<String> screenCatalogIds = configOrgRegulatoryDiscretionMapper.screenCatalogIds(orgConfig.getSsfj());
        if (Constant.STRING_0.equals(alreadyCityConfig)) {
            // 未配置，排除法 有规则配置的catalogId 塞入excludesCatalogIds中
            scopeDto.setExcludesCatalogIds(new HashSet<>(screenCatalogIds));
            return scopeDto;
        }
        //如果查询出不存在自由裁量配置事项 需要给查询的id集合加入值，防止全部查出
        if (CollUtil.isEmpty(screenCatalogIds)) {
            //若数据为空，则需要手动添加一个includeCatalogIds，防止检查查出所有数据
            screenCatalogIds.add(Constant.STRING_0);
        }
        scopeDto.setCatalogIds(new HashSet<>(screenCatalogIds));
        return scopeDto;
    }

    /**
     * 筛选禁用启用
     */
    private DiscretionScreenRangeDto screenDiscretionType(DiscretionTypeEnum discretionType) {
        DiscretionScreenRangeDto scopeDto = new DiscretionScreenRangeDto();
        if (Objects.isNull(discretionType)) {
            return scopeDto;
        }
        Example example = new Example(ConfigOrgRegulatoryDiscretion.class);
        example.createCriteria()
                .andEqualTo("orgCode", orgConfig.getSsfj())
                .andEqualTo("discretionType", DiscretionTypeEnum.CITY.getCode());
        //查询出数据库存在的自由裁量配置事项集合
        List<String> regulatoryCatalogIds = configOrgRegulatoryDiscretionMapper.selectByExample(example)
                .stream().map(ConfigOrgRegulatoryDiscretion::getRegulatoryCatalogId).collect(Collectors.toList());
        // 如果是禁用，因为处罚只有启动的数据所以如果是禁用 则需要将查出来的数据排除掉
        if (DiscretionTypeEnum.NONE.equals(discretionType)) {
            scopeDto.setExcludesCatalogIds(new HashSet<>(regulatoryCatalogIds));
            return scopeDto;
        }
        //如果查询出不存在自由裁量配置事项 需要给查询的id集合加入值，防止全部查出
        if (CollUtil.isEmpty(regulatoryCatalogIds)) {
            //若数据为空，则需要手动添加一个includeCatalogIds，防止检查查出所有数据
            regulatoryCatalogIds.add(Constant.STRING_0);
        }
        scopeDto.setCatalogIds(new HashSet<>(regulatoryCatalogIds));
        return scopeDto;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(ConfigOrgRegulatoryDiscretionSaveDto dto) {
        UserDTO user = getUser();
        // 排除非市司法局的请求
        if (!orgConfig.getSsfj().equals(user.getOrgCode())) {
            throw new BusinessException("用户无权限！");
        }
        // 得到该事项的处罚适用类型
        List<String> punishTypes = userCenterClient.getPunishTypeByCatalogId(dto.getRegulatoryCatalogId());
        //校验参数
        dto.check(punishTypes);
        String regulatoryCatalogId = dto.getRegulatoryCatalogId();
        //保存并获取自由裁量配置数据
        ConfigOrgRegulatoryDiscretion discretion = saveAndGetCurrentOrgDiscretion(regulatoryCatalogId);
        // 对自由裁量规则进行处理（新增、修改、删除）
        configOrgRegulatoryDiscretionRuleService.handleDiscretionRuleInfo(discretion, dto.getPersonalRules(),
                dto.getOrgRules(), DiscretionRuleConfigTypeEnum.CITY);
        // 进行停用禁用的配置修改
        chooseDiscretionType(new RegulatoryChooseDiscretionTypeDto(dto.getRegulatoryCatalogId(), dto.getDiscretionType()));
    }


    /**
     * 保存并获取当前部门自由裁量配置数据
     *
     * @param regulatoryCatalogId 事项catalogId
     * @return
     */
    private ConfigOrgRegulatoryDiscretion saveAndGetCurrentOrgDiscretion(String regulatoryCatalogId) {
        ConfigOrgRegulatoryDiscretion discretion = getCurrentOrgDiscretionByCatalogId(regulatoryCatalogId);
        if (Objects.isNull(discretion)) {
            discretion = insertMainDiscretion(regulatoryCatalogId);
        }
        return discretion;
    }

    /**
     * 根据catalogId 与 orgCode获取自由裁量主表信息
     */
    private ConfigOrgRegulatoryDiscretion getCurrentOrgDiscretionByCatalogId(String catalogId) {
        ConfigOrgRegulatoryDiscretion queryDiscretion = new ConfigOrgRegulatoryDiscretion();
        queryDiscretion.setRegulatoryCatalogId(catalogId);
        //只有市司法局自由裁量配置
        queryDiscretion.setOrgCode(orgConfig.getSsfj());
        return configOrgRegulatoryDiscretionMapper.selectOne(queryDiscretion);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void chooseDiscretionType(RegulatoryChooseDiscretionTypeDto dto) {
        UserDTO user = getUser();
        // 排除非市司法局的请求
        if (!orgConfig.getSsfj().equals(user.getOrgCode())) {
            throw new BusinessException("用户无权限！");
        }
        dto.legality();
        ConfigOrgRegulatoryDiscretion discretion = saveAndGetCurrentOrgDiscretion(dto.getRegulatoryCatalogId());
        if (dto.getDiscretionType().getCode().equals(discretion.getDiscretionType())) {
            //启用标准相同无需操作
            return;
        }
        discretion.setDiscretionType(dto.getDiscretionType().getCode());
        discretion.setUpdateTime(new Date());
        discretion.setUpdateUser(user.getRealName());
        configOrgRegulatoryDiscretionMapper.updateByPrimaryKeySelective(discretion);
    }

    @Override
    public List<ConfigOrgRegulatoryDiscretionRuleVo> getRuleListByCaseReasonAndParty(DiscretionRuleListByCaseReasonAndPartyDto dto) {
        if (StrUtil.isEmpty(dto.getPartyId()) && Objects.isNull(dto.getPartyType())) {
            throw new BusinessException("当事人id与当事人类型不能同时为空");
        }
        //查询案由
        CaseReasonMainRecordVo caseReasonRecord = caseReasonMainRecordService.getCaseReasonRecord(dto.getCaseReasonId());
        String busId = checkAndGetBusIdByCaseReason(caseReasonRecord);

        DiscretionRuleApplyTypeEnum applyType = DiscretionRuleApplyTypeEnum.convertByPartyType(dto.getPartyType());
        if (Objects.isNull(applyType)) {
            //当适用范围为null时说明前端没有传partyType，此时根据partyId查询
            CasePartiesRecordVo partyRecord = casePartiesRecordService.getCasePartiesInfoByPartyId(caseReasonRecord.getCaseId(), dto.getPartyId());
            applyType = DiscretionRuleApplyTypeEnum.convertByPartyType(PartyTypeEnum.getByCode(partyRecord.getPartyType()));
        }
        //获取转换事项catalogId
        String catalogId = userCenterClient.getCatalogIdByBusId(busId);
        //获取配置规则
        return getRuleListByCatalogIdAndApplyType(catalogId, applyType, dto.getApplyCaseType(), null);
    }

    @Override
    public List<ConfigOrgRegulatoryDiscretionRuleVo> getMergeRuleListByCase(DiscretionRuleListByCaseDto dto) {
        //只有多当事人单事项的时候会触发合并处罚
        //获取当前案件所有的当事人类型
        List<CasePartiesRecordVo> partiesRecordList = casePartiesRecordService.getCasePartiesInfoVoList(dto.getCaseId());
        List<PartyTypeEnum> partyTypes = partiesRecordList.stream().map(CasePartiesRecordVo::getPartyType)
                .filter(Objects::nonNull).distinct().map(PartyTypeEnum::getByCode).collect(Collectors.toList());
        //转换为适用范围
        List<DiscretionRuleApplyTypeEnum> applyTypes = partyTypes.stream()
                .map(DiscretionRuleApplyTypeEnum::convertByPartyType).collect(Collectors.toList());
        if (CollUtil.isEmpty(applyTypes)) {
            //适用范围为空时不需要查询
            return Collections.emptyList();
        }
        String catalogId = dto.getRegulatoryCatalogId();
        //当未指定事项唯一id时根据案件查询事项busId转换为catalogId
        if (StrUtil.isEmpty(catalogId)) {
            //获取案由的事项busId
            CaseReasonMainRecordVo caseReasonRecord = caseReasonMainRecordService.getCaseReasonRecordByCaseId(dto.getCaseId());
            String busId = checkAndGetBusIdByCaseReason(caseReasonRecord);
            //获取转换事项catalogId
            catalogId = userCenterClient.getCatalogIdByBusId(busId);
        }
        String orgCode = getOrgCodeByCatalogId(catalogId);
        if (Objects.isNull(orgCode)) {
            //没有部门code时，说明没有对应的事项自由裁量配置或未启用配置
            return Collections.emptyList();
        }
        return configOrgRegulatoryDiscretionRuleService.getByOrgAndCatalogIdAndApplyTypes(orgCode, catalogId, applyTypes, dto.getApplyCaseType());
    }

    @Override
    public List<ConfigOrgRegulatoryDiscretionRuleVo> getRuleListByRegulatoryAndParty(DiscretionRuleListByRegulatoryAndPartyDto dto) {
        if (StrUtil.isEmpty(dto.getPartyId()) && Objects.isNull(dto.getPartyType())) {
            throw new BusinessException("当事人id与当事人类型不能同时为空");
        }

        DiscretionRuleApplyTypeEnum applyType = DiscretionRuleApplyTypeEnum.convertByPartyType(dto.getPartyType());
        if (Objects.isNull(applyType)) {
            //当适用范围为null时说明前端没有传partyType，此时根据partyId查询
            CasePartiesRecordVo partyRecord = casePartiesRecordService.getCasePartiesInfoByPartyId(null, dto.getPartyId());
            applyType = DiscretionRuleApplyTypeEnum.convertByPartyType(PartyTypeEnum.getByCode(partyRecord.getPartyType()));
        }
        //获取配置规则
        return getRuleListByCatalogIdAndApplyType(dto.getRegulatoryCatalogId(), applyType, dto.getApplyCaseType(), dto.getClientOrgCode());
    }

    @Override
    public List<ConfigOrgRegulatoryDiscretionRuleVo> getRuleListByBusIdAndParty(DiscretionRuleListByBusIdAndPartyDto dto) {
        // 转换catalogId
        String catalogId = userCenterClient.getCatalogIdByBusId(dto.getBusId());
        // 组装参数
        DiscretionRuleListByRegulatoryAndPartyDto param = new DiscretionRuleListByRegulatoryAndPartyDto();
        param.setRegulatoryCatalogId(catalogId);
        param.setPartyId(dto.getPartyId());
        param.setClientOrgCode(dto.getClientOrgCode());
        param.setPartyType(dto.getPartyType());
        param.setApplyCaseType(dto.getApplyCaseType());
        return getRuleListByRegulatoryAndParty(param);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refreshUpdateInfo(String id) {
        UserDTO user = getUser();
        ConfigOrgRegulatoryDiscretion discretion = configOrgRegulatoryDiscretionMapper.selectByPrimaryKey(id);
        if (Objects.isNull(discretion)) {
            throw new BusinessException("没有找到自由裁量配置信息");
        }
        discretion.setUpdateTime(new Date());
        discretion.setUpdateUser(user.getRealName());
        configOrgRegulatoryDiscretionMapper.updateByPrimaryKeySelective(discretion);
    }

    /**
     * 根据事项id和适用范围查询当前部门规则集合
     *
     * @param catalogId     事项id
     * @param applyType     适用范围
     * @param assignOrgCode 指定部门编码
     * @return
     */
    private List<ConfigOrgRegulatoryDiscretionRuleVo> getRuleListByCatalogIdAndApplyType(String catalogId,
                                                                                         DiscretionRuleApplyTypeEnum applyType,
                                                                                         DiscretionApplyCaseTypeEnum applyCaseType,
                                                                                         String assignOrgCode) {
        String orgCode = StrUtil.isNotEmpty(assignOrgCode) ? assignOrgCode : getOrgCodeByCatalogId(catalogId);
        if (Objects.isNull(orgCode)) {
            //没有部门code时，说明没有对应的事项自由裁量配置或未启用配置
            return Collections.emptyList();
        }
        //获取违法情形列表
        return configOrgRegulatoryDiscretionRuleService.getByOrgAndApplyTypeAndCatalogId(orgCode, applyType, applyCaseType, catalogId);
    }


    /**
     * 根据不同的自由裁量启用标准 返回不同的部门code
     *
     * @param catalogId 事项catalogId
     * @return 对应的orgCode，若orgCode为null代表没有对应的事项自由裁量配置或未启用配置
     */
    private String getOrgCodeByCatalogId(String catalogId) {
        ConfigOrgRegulatoryDiscretion discretion = getCurrentOrgDiscretionByCatalogId(catalogId);
        if (Objects.isNull(discretion) || DiscretionTypeEnum.NONE.getCode().equals(discretion.getDiscretionType())) {
            return null;
        }
        return orgConfig.getSsfj();
    }

    /**
     * 根据案由获取事项busId
     *
     * @return 事项busId
     */
    private String checkAndGetBusIdByCaseReason(CaseReasonMainRecordVo caseReasonRecord) {
        if (Objects.isNull(caseReasonRecord)) {
            throw new BusinessException("没有获取到案由信息！");
        }
        String caseReasonNodeid = caseReasonRecord.getCaseReasonNodeid();
        if (StrUtil.isEmpty(caseReasonNodeid)) {
            throw new BusinessException("当前案由没有存放事项数据！");
        }
        String[] nodeIds = caseReasonNodeid.split(",");
        //0-事项类型 1-事项busId
        if (nodeIds.length < 2) {
            throw new BusinessException("当前案由没有存放事项数据！");
        }
        return nodeIds[1];
    }


    @Override
    public ConfigOrgRegulatoryDiscretionDetailVo detail(String regulatoryCatalogId) {
        if (StrUtil.isEmpty(regulatoryCatalogId)) {
            throw new BusinessException("事项catalogId不能为空");
        }
        //根据事项id查询规则集合
        List<ConfigOrgRegulatoryDiscretionRule> rules = configOrgRegulatoryDiscretionRuleService.getCurrentOrgRuleByCatalogIds(Collections.singletonList(regulatoryCatalogId));
        ConfigOrgRegulatoryDiscretionDetailVo vo = new ConfigOrgRegulatoryDiscretionDetailVo();
        vo.setOrgRules(rules.stream()
                .filter(t -> DiscretionRuleApplyTypeEnum.ORG.getCode().equals(t.getApplyType()))
                .sorted(Comparator.comparing(ConfigOrgRegulatoryDiscretionRule::getSort))
                .map(ConfigOrgRegulatoryDiscretionRuleVo::new).collect(Collectors.toList()));
        vo.setPersonalRules(rules.stream()
                .filter(t -> DiscretionRuleApplyTypeEnum.PERSONAL.getCode().equals(t.getApplyType()))
                .sorted(Comparator.comparing(ConfigOrgRegulatoryDiscretionRule::getSort))
                .map(ConfigOrgRegulatoryDiscretionRuleVo::new).collect(Collectors.toList()));
        return vo;
    }

    /**
     * 新增自由裁量主表
     */
    private ConfigOrgRegulatoryDiscretion insertMainDiscretion(String catalogId) {
        UserDTO user = getUser();
        ConfigOrgRegulatoryDiscretion newDiscretion = new ConfigOrgRegulatoryDiscretion();
        newDiscretion.setId(StringUtils.uuid());
        newDiscretion.setOrgCode(user.getOrgCode());
        newDiscretion.setRegulatoryCatalogId(catalogId);
        newDiscretion.setDiscretionType(DiscretionTypeEnum.NONE.getCode());
        newDiscretion.setCreateTime(new Date());
        newDiscretion.setCreateUser(user.getRealName());
        newDiscretion.setUpdateTime(new Date());
        newDiscretion.setUpdateUser(user.getRealName());
        configOrgRegulatoryDiscretionMapper.insert(newDiscretion);
        return newDiscretion;
    }
}




